// pages/fileAdd/index.js
import {saveRecords,getYaofang,get_order_status} from '../../api/api'
import { getToken } from '../../utils/storage.js'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    _tongueList: [],
    _otherList: [],
    tongueList: [], // 上传后的舌像
    otherList: [],  // 上传后的其他
    inputRemarks: ''
  },

  // 输入癌症备注
  inputRemark(e){
    this.setData({inputRemarks: e.detail.value})
  },
  // 预览舌像
  seeTongue(){
    wx.previewImage({
        current: 0,//当前点击的图片链接
        urls: this.data._tongueList//图片数组
    })
  },
  // 预览其他
  seeOther(){
    wx.previewImage({
        current: 0,//当前点击的图片链接
        urls: this.data._otherList//图片数组
    })
  },
  // 舌像
  addImg1(){
    let that= this
    wx.chooseMedia({
      count: 9,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success(res) {
        that.setData({
          _tongueList:res.tempFiles
        })
      }
    })
  },
  // 其他医学类图片
  addImg2(){
    let that= this
    wx.chooseMedia({
      count: 9,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success(res) {
        that.setData({
          _otherList:res.tempFiles
        })

        console.log(res);
        // console.log(res.tempFiles.tempFilePath)
        // this.uploadImg(res.tempFiles.tempFilePath)
        // console.log(res.tempFiles.size)
      }
    })
  },
  // 上传图片
  uploadImg(tempFilePaths){
    return new Promise(function (resolve,reject) {
      let header = {
        'content-type': 'application/json',
        "Authorization":  getToken() //携带token在请求头中
      };
      wx.uploadFile({
        url: 'https://ykbwxapp.icanbo.com.cn/index.php/patient/index/uploadImg', //仅为示例，非真实的接口地址
        filePath: tempFilePaths,
        header,
        name: 'file',
        success (res){
          console.log(res);
          res.data = JSON.parse(res.data)
          if (res.data.code === 200) {
            resolve(res.data);
          } else if (res.data.code === 500) {
            //登录状态失效，需要重新刷新数据
             reject('登录状态失效，需要重新刷新数据');
          } else if (res.data.code === 301) {
            //登录状态失效，需要重新刷新数据
            wx.navigateTo({
              url: '/pages/login/index',
            })
             reject('登录状态失效，需要重新刷新数据');
          } else {
            //其他异常
            reject('运行时错误,请稍后再试');
          }
        }
      })
    })
  },
  // 去看药方
  async payment(){
    // 上传舌象图片
    let tongueList = []
    let _tongueList = this.data._tongueList

    for(let i in _tongueList){
      let img_res = await this.uploadImg(_tongueList[i].tempFilePath)
      let imgurl = img_res.data.url

      console.log(imgurl);

      tongueList.push(imgurl)
    }

    // 上传其他图片
    let otherList = []
    let _otherList = this.data._otherList

    for(let i in _otherList){
      let img_res = await this.uploadImg(_otherList[i].tempFilePath)
      let imgurl = img_res.data.url
      otherList.push(imgurl)
    }

    console.log(tongueList,otherList);

    const data = {
      tongue: tongueList.join(','),
      otherRecords: otherList.join(','),
      text1: JSON.stringify({classesList: getApp().globalData.datalist}),
      remark: this.data.inputRemarks
    }

    saveRecords(data).then(res => {
      if(res.data.code === 200) {
        // console.log(res1);

        wx.requestPayment({
          timeStamp:res.data.data.timeStamp,
          nonceStr:res.data.data.nonceStr,
          package:res.data.data.package,
          signType:res.data.data.signType,
          paySign:res.data.data.paySign,
          success(res1) {
            let params = {order_num:res.data.data.order_num}
            console.log(params)
            // 支付成功回调
            get_order_status(params).then((res1)=>{
              console.log(res1);

              if(res1.data.data==1){
                console.log('支付成功', res1);

                wx.reLaunch({
                  url: '/pages/prescription/index',
                })
              }
            })

            // data.success(res)
          },
          fail(res2) {
            // 支付失败回调
            console.log('支付失败', res2);
            // data.fail(res)
          }
        });
      }
    })

    // place_an_order().then(res => {
    //   console.log(res.data.data);

    //   console.log(res);
    // })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})